package cn.avalon.pet.service.impl;

import cn.avalon.basic.exception.BusinessException;
import cn.avalon.basic.service.BaiduAiAuditService;
import cn.avalon.basic.service.impl.BaseServiceImpl;
import cn.avalon.basic.utils.*;
import cn.avalon.order.domain.OrderPetAcquisition;
import cn.avalon.order.listener.DelayProduce;
import cn.avalon.order.mapper.OrderPetAcquisitionMapper;
import cn.avalon.org.domain.Employee;
import cn.avalon.org.domain.Shop;
import cn.avalon.org.mapper.EmployeeMapper;
import cn.avalon.org.mapper.ShopMapper;
import cn.avalon.pet.domain.Pet;
import cn.avalon.pet.domain.SearchMasterMsg;
import cn.avalon.pet.domain.SearchMasterMsgAuditLog;
import cn.avalon.pet.mapper.PetMapper;
import cn.avalon.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.avalon.pet.mapper.SearchMasterMsgMapper;
import cn.avalon.pet.query.SearchMasterMsgQuery;
import cn.avalon.pet.service.ISearchMasterMsgService;
import cn.avalon.user.domain.Logininfo;
import cn.avalon.user.domain.User;
import cn.avalon.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private BaiduAiAuditService baiduAiAuditService;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private DelayProduce delayProduce;

    @Override
    public AjaxResult publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        //        id        -   自增长
        //        name      -   来自页面
        //        age       -   来自页面
        //        gender    -   来自页面
        //        coat_color-   来自页面
        //        resources -   来自页面
        //        pet_type  -   来自页面
        //        price     -   来自页面
        //        address   -   来自页面
        //        state     -   来自实体默认值 //0表示待审核或驳回， 1表示已审核待处理，2表示处理成功，3拒
        //        title     -   来自页面
        //        user_id   -   谁发布的寻主消息 = 用户 = 登录了才能发布
        //        shop_id   -   获取最近的门店的id

        //1.获取登录人id
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.findByLogininfoId(logininfo.getId());
        searchMasterMsg.setUserId(user.getId());

        searchMasterMsg.setState(0);//待审核 - 可以不设置

        //2.将寻主消息添加到数据库- 如何审核失败 - 修改寻主消息重新审核【shop_id】
        searchMasterMsgMapper.save(searchMasterMsg); //自增ID

        //3.百度AI智能审核
        Boolean textBoo = baiduAiAuditService.textAudit(searchMasterMsg.getTitle() + searchMasterMsg.getName() + searchMasterMsg.getAddress());
        Boolean imageBoo = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());
        //3.1.审核成功
        if(textBoo && imageBoo) {//成功
            //a.修改状态：0 - 1
            searchMasterMsg.setState(1);//审核通过待处理
            searchMasterMsg.setNote("审核成功");
            //b1.找到最近的店铺 - 分配店铺【设置到shopId】 - 发送短信给店铺管理员，告诉他去接回宠物
            List<Shop> shops = shopMapper.findAll();
            System.out.println(shops);
            Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());//用户发布寻主消息的地址 - 宠物的地址
            Shop nearestShop = DistanceUtils.getNearestShop(point, shops);
            //b2.找到店铺 - 绑定店铺 。没有周到就放到寻主池[state=1,shopId=null]
            if(nearestShop!=null){
                searchMasterMsg.setShopId(nearestShop.getId());
            }
            //b3.更新数据库
            searchMasterMsgMapper.update(searchMasterMsg);
            //c.添加审核成功日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            log.setState(1);//审核成功
            //百度智能审核
            log.setNote("审核成功");
            searchMasterMsgAuditLogMapper.save(log);
            if(nearestShop!=null){
                Employee employee = employeeMapper.findByShopId(nearestShop.getId());
                //SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请去"+msg.getAddress()+"接回宠物!!!");
                System.out.println("你有新的订单，请去"+searchMasterMsg.getAddress()+"接回宠物!!!");
            }
            return new AjaxResult();
        } else {
            //3.2.审核失败
            //a.添加审核失败日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            log.setState(0);//审核失败
            //百度智能审核
            log.setNote("审核失败");
            searchMasterMsgAuditLogMapper.save(log);
            //b.发送短信给用户告诉他审核失败，修改寻主消息
//            SmsUtils.sendSms(user.getPhone(),"你发布的寻主消息未通过审核，请修改之后重新发布!!!");
            System.out.println("你发布的寻主消息未通过审核，请修改之后重新发布!!!");
            return AjaxResult.me().setSuccess(false).setMsg("审核失败");
        }
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        //判断当前登录人是平台管理员还是店铺管理员。如果是平台管理员还要设置shopId
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());

        //根据emp中是否有shopid - 判断平台管理员还是店铺管理员
        //loginInfo里面的type - 判断用户或管理员
        if(employee.getShop_id()!=null){//店铺管理员
            query.setShopId(employee.getShop_id());
        }

        return super.queryPage(query);
        //如果是平台管理员：state = 1 - 接口中
        //如果是店铺管理员：state = 1 并且 shopId = x
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        //判断当前登录人是平台管理员还是店铺管理员。如果是平台管理员还要设置shopId
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());

        //根据emp中是否有shopid - 判断平台管理员还是店铺管理员
        //loginInfo里面的type - 判断用户或管理员
        if(employee.getShop_id()!=null){//店铺管理员
            query.setShopId(employee.getShop_id());
        }

        return super.queryPage(query);
        //如果是平台管理员：state = 1 - 接口中
        //如果是店铺管理员：state = 1 并且 shopId = x
    }

    @Override
    @Transactional
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    @Override
    @Transactional
    public void accept(Map<String, String> params) {

        long msgId = Long.parseLong(params.get("msgId"));
        long EmpId = Long.parseLong(params.get("handler"));

        //1.校验改寻主消息是否已经在处理，报错
        OrderPetAcquisition orderTmp = orderPetAcquisitionMapper.findByMsgId(msgId);
        if (orderTmp != null) {
            throw new BusinessException("已经被接单，正在处理中！");
        }

        //处理人id
        Employee handler = employeeMapper.findById(EmpId);

        //1 创建寻主消息所对应宠物信息
        //1.1 获取寻主消息
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findById(msgId);
        // 这一段代码用于在寻主池接单，给订单增加店铺
        if (searchMasterMsg.getShop() == null) {
            searchMasterMsg.setShopId(employeeMapper.findById(EmpId).getShop_id());
            searchMasterMsgMapper.update(searchMasterMsg);
        }
        searchMasterMsgMapper.update(searchMasterMsg);
        //1.2 创建宠物信息
        Pet pet = searchMasterMsg2Pet(searchMasterMsg);
        petMapper.save(pet);

        //2 创建宠物收购订单
        OrderPetAcquisition order = buildPetAcquisitionOrder(searchMasterMsg,handler,pet);
        delayProduce.sendDelayMessage("delay-topic",order.getSearchMasterMsgId().toString(),19);

        orderPetAcquisitionMapper.save(order);

        //3 发送消息给对应的工作人员
        System.out.println(handler.getEmail()+"-->邮件通知：您有新的"+order.getOrderSn()+"订单要处理！");
    }

    private OrderPetAcquisition buildPetAcquisitionOrder(SearchMasterMsg searchMasterMsg, Employee handler, Pet pet) {

        OrderPetAcquisition order = new OrderPetAcquisition();

        String orderSn = CodeGenerateUtils.generateOrderSn(handler.getId());

        order.setOrderSn(orderSn);

        order.setDigest(searchMasterMsg.getName() + "的收购订单");

        //最后收购是当前时间+2两天
        order.setLastcomfirmtime(new Date(System.currentTimeMillis() + 1000*60*60*24*2));

        order.setState(0);

        order.setPrice(searchMasterMsg.getPrice());

        order.setPetId(pet.getId());

        order.setUserId(searchMasterMsg.getUserId());

        order.setShopId(pet.getShopId());

        order.setAddress(searchMasterMsg.getAddress());

        order.setEmpId(handler.getId());

        order.setSearchMasterMsgId(searchMasterMsg.getId());

        return order;
    }

    private Pet searchMasterMsg2Pet(SearchMasterMsg searchMasterMsg) {
        Pet pet = new Pet();
        pet.setName(searchMasterMsg.getName());
        pet.setResources(searchMasterMsg.getResources());
        pet.setTypeId(searchMasterMsg.getPetType());
        //就要获取处理人的店铺id
        pet.setShopId(searchMasterMsg.getShopId());
        pet.setUserId(searchMasterMsg.getUserId());
        pet.setSearchMasterMsgId(searchMasterMsg.getId());
        //用户发布时需要的价格 收购回来就是成本价
        pet.setCostprice(searchMasterMsg.getPrice());
        return pet;
    }
}
